﻿//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2011 , JamSoft TECH, Ltd .
//-------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

// 本系统生成的类库
using DotNet.Business;
using DotNet.Utilities;

/// <remarks>
/// Registration
/// 用户注册
/// 
/// 修改纪录
///	版本：1.0 2011.09.01 LiangMingMing  创建代码。 
/// <author>
///     <verison>1.0</verison>
///		<name>LiangMingMing</name>
///		<date>2011.09.01</date>
///		<description>用户注册</description>
/// </author> 
/// </remarks>
public partial class Registration : BasePage
{
    // **********************************************************************************************
    // *                                                                                            * 
    // *                             Public Variate    公共变量                                     *
    // *                                                                                            * 
    // **********************************************************************************************

    /// <summary>
    /// 多语言变量（添加到收藏夹）
    /// </summary>
    public string ToolbarFavorite = string.Empty;
    /// <summary>
    /// 多语言变量（显示隐藏左边菜单）
    /// </summary>
    public string ToolbarShowhideLeftFrame = string.Empty;
    /// <summary>
    /// 多语言变量（显示隐藏TOP页面）
    /// </summary>
    public string ToolbarShowhideTopFrame = string.Empty;
    /// <summary>
    /// 多语言变量（帮助中心）
    /// </summary>
    public string ToolbarHelp = string.Empty;
    /// <summary>
    /// 多语言-按钮（保存）
    /// </summary>
    public string ButtonConfirm = string.Empty;
    /// <summary>
    /// 多语言-按钮（返回）
    /// </summary>
    public string ButtonReturn = string.Empty;
    /// <summary>
    /// 多语言-按钮（取消）
    /// </summary>
    public string ButtonCancel = string.Empty;
    /// <summary>
    /// 注册用户需要审核
    /// </summary>
    private bool CheckRegisterUser = false;
    /// <summary>
    /// 返回页面
    /// </summary>
    public string ReturnPage
    {
        get
        {
            return this.txtReturnPage.Value;
        }
        set
        {
            this.txtReturnPage.Value = value;
        }
    }

    // **********************************************************************************************
    // *                                                                                            * 
    // *                             InitializeComponent  初始化                                    * 
    // *                                                                                            * 
    // **********************************************************************************************

    #region private void PageOnLoad() 页面初次加载时的动作
    /// <summary>
    /// 页面初次加载时的动作
    /// </summary>
    private void PageOnLoad()
    {
        this.GetItemDetails();
        this.GetParamter();
        this.SetButtomState();
    }
    #endregion

    // **********************************************************************************************
    // *                                                                                            * 
    // *                                       Method   操作方法                                    * 
    // *                                                                                            * 
    // **********************************************************************************************


    #region private void Localization() 多语言国际化加载
    /// <summary>
    /// 多语言国际化加载
    /// </summary>
    private void Localization()
    {
        // 多语言国际化加载
        ResourceManagerWrapper.Instance.LoadResources(Server.MapPath("../../../../Resource/Localization/"));
        // 获取语言信息
        this.GetLanguageResource(Utilities.GetCurrentLanguage(this.UserInfo));
    }
    #endregion

    #region private void GetLanguageResource(string languages) 获取语言
    /// <summary>
    /// 获取语言
    /// </summary>
    /// <param name="languages">语言类型</param>
    private void GetLanguageResource(string languages)
    {
        /// <以变量形式加载，刷新时会被刷掉所以得一直加载着>
        // 添加到收藏夹
        this.ToolbarFavorite = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.Favorite");
        // 显示隐藏左边菜单
        this.ToolbarShowhideLeftFrame = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.ShowhideLeftFrame");
        // 显示隐藏TOP页面
        this.ToolbarShowhideTopFrame = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.ShowhideTopFrame");
        // 帮助中心
        this.ToolbarHelp = ResourceManagerWrapper.Instance.Get(languages, "Toolbar.Help");
        // 按钮-保存
        this.ButtonConfirm = ResourceManagerWrapper.Instance.Get(languages, "Button.Save");
        // 按钮-返回
        this.ButtonReturn = ResourceManagerWrapper.Instance.Get(languages, "Button.Return");
        // 按钮-取消
        this.ButtonCancel = ResourceManagerWrapper.Instance.Get(languages, "Button.Cancel");
        /// <用的是控件，所以不怕被刷新>
        if (!Page.IsPostBack)
        {
            // 标题
            this.Title = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx");
            // 确认密码：
            this.ltlConfirmPassword.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlConfirmPassword");
            // 备注：
            this.ltlDescription.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlDescription");
            // 电子邮件
            this.ltlEmail.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlEmail");
            // 密码
            this.ltlPassword.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlPassword");
            // 真实姓名
            this.ltlRealName.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlRealName");
            // 默认角色
            this.ltlRole.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlRole");
            // 标题名称 - 用户注册
            this.ltlTittle.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlTittle");
            // 用户名
            this.ltlUserName.Text = ResourceManagerWrapper.Instance.Get(languages, "Registration.aspx_ltlUserName");
            // 下拉框请选择
            this.txtPleseSelect.Value = ResourceManagerWrapper.Instance.Get(languages, "DropDownList.Select");
            // 提示信息：E_mail 格式不正确，请重新输入。
            this.hdfEmail.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50010");
            // 提示信息:请输入密码。
            this.hdfMiMa.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50011");
            // 提示信息:确认密码不正确，请重新输入。
            this.hdfQueRenMiMa.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50012");
            // 提示信息：请选择默认用户角色。
            this.hdfRole.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50013");
            // 提示信息:请输入用户名。
            this.hdfYongHuMing.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50014");
            // 提示信息:用户已存,在不可以重复。
            this.hdfUserNameExits.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50031");
            // 提示信息:编号已存在,不可以重复。
            this.hdfUserCodeExtis.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50032");
            // 提示信息:保存成功。
            this.hdfUserSaveSucess.Value = ResourceManagerWrapper.Instance.Get(languages, "MSG50001");
        }
    }
    #endregion

    #region private void GetParamter() 读取参数
    /// <summary>
    /// 读取参数
    /// </summary>
    private void GetParamter()
    {
        if (Page.Request["ReturnPage"] != null)
        {
            this.txtReturnPage.Value = Page.Request["ReturnPage"].ToString();
        }
        if (Page.Request["Role"] != null)
        {
            this.cmbRole.SelectedValue = Page.Request["Role"].ToString();
        }
    }
    #endregion

    #region private void SetButtomState() 设置按钮状态
    /// <summary>
    /// 设置按钮状态
    /// </summary>
    private void SetButtomState()
    {
        this.btnReturn.Visible = !string.IsNullOrEmpty(this.ReturnPage);
    }
    #endregion

    #region private void GetItemDetails() 绑定下拉筐数据
    /// <summary>
    /// 绑定下拉筐数据
    /// </summary>
    private void GetItemDetails()
    {
        // 添加一项提示项
        ListItem listItem = new ListItem(this.txtPleseSelect.Value, string.Empty);
        // this.cmbRole.Items.Add(new ListItem() { Text = "请选择用户角色" });
        this.cmbRole.Items.Add(listItem);
        this.cmbRole.AppendDataBoundItems = true;
        DotNetService dotNetService = new DotNetService();
        DataTable dataTable = dotNetService.RoleService.GetDataTable(this.UserInfo);
        // 绑定角色
        this.cmbRole.DataSource = dataTable;
        this.cmbRole.DataTextField = BaseRoleEntity.FieldRealName;
        this.cmbRole.DataValueField = BaseRoleEntity.FieldId;
        this.cmbRole.DataBind();
    }
    #endregion

    #region private bool CheckInput() 检查页面输入
    /// <summary>
    /// 检查页面输入
    /// </summary>
    /// <returns>是否正确</returns>
    private bool CheckInput()
    {
        bool returnValue = true;
        string checkInput = string.Empty;
        if (this.txtUserName.Text.Trim().Length == 0)
        {
            checkInput = "<script>alert('" + this.hdfYongHuMing.Value + "'); document.getElementById('" + this.txtUserName.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        if (this.txtPassword.Text.Trim().Length == 0)
        {
            checkInput = "<script>alert('" + this.hdfMiMa.Value + "'); document.getElementById('" + this.txtPassword.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        if (!this.txtPassword.Text.Trim().Equals(this.txtConfirmPassword.Text.Trim()))
        {
            checkInput = "<script>alert('" + this.hdfQueRenMiMa.Value + "'); document.getElementById('" + this.txtConfirmPassword.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        if (this.txtEmail.Text.Trim().Length > 0)
        {
            if (!ValidateUtil.IsEmail(this.txtEmail.Text.Trim()))
            {
                checkInput = "<script>alert('" + this.hdfEmail.Value + "'); document.getElementById('" + this.txtEmail.ClientID + "').focus();</script>";
                ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
                return false;
            }
        }
        if (this.cmbRole.SelectedIndex < 1)
        {
            checkInput = "<script>alert('" + this.hdfRole.Value + "');document.getElementById('" + this.cmbRole.ClientID + "').focus();</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
            return false;
        }
        return returnValue;
    }
    #endregion

    #region private BaseUserEntity GetUserEntity() 获取用户注册信息
    /// <summary>
    /// 获取用户注册信息
    /// </summary>
    /// <returns>用户实体</returns>
    private BaseUserEntity GetUserEntity()
    {
        BaseUserEntity userEntity = new BaseUserEntity();
        userEntity.UserName = this.txtUserName.Text;
        userEntity.UserPassword = this.txtPassword.Text;
        userEntity.RealName = this.txtRealName.Text;
        userEntity.RoleId = int.Parse(this.cmbRole.SelectedValue);
        userEntity.Email = this.txtEmail.Text;
        userEntity.Description = this.txtDescription.Text;
        userEntity.Enabled = CheckRegisterUser ? 0 : 1;
        if (CheckRegisterUser)
        {
            userEntity.AuditStatus = AuditStatus.WaitForAudit.ToString();
        }
        return userEntity;
    }
    #endregion

    // **********************************************************************************************
    // *                                                                                            * 
    // *                                       EventArgs    事件方法                                * 
    // *                                                                                            * 
    // **********************************************************************************************

    #region protected void Page_Load(object sender, EventArgs e) 页面初次加载的动作
    /// <summary>
    /// 页面初次加载的动作
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        // 多语言国际化加载
        this.Localization();
        if (!Page.IsPostBack)
        {
            // 加载页面动作
            this.PageOnLoad();
            // 设置焦点
            this.txtUserName.Focus();
        }
    }
    #endregion

    #region protected void btnRegister_Click(object sender, EventArgs e) 注册
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        this.lblPrompt.Text = string.Empty;
        if (this.CheckInput())
        {
            try
            {
                string returnStatusCode = string.Empty;
                string returnStatusMessage = string.Empty;
                // 默认是需要审核
                BaseUserEntity userEntity = this.GetUserEntity();
                DotNetService dotNetService = new DotNetService();
                dotNetService.UserService.AddUser(this.UserInfo, userEntity, out returnStatusCode, out returnStatusMessage);
                // 注册结果
                if (returnStatusCode.Equals(StatusCode.OKAdd.ToString()))
                {
                    this.lblPrompt.Text = returnStatusMessage;
                    ScriptUtil.AlertAndRedirect(this.hdfUserSaveSucess.Value, this.ReturnPage);
                }
                else
                {
                    // 用户名重复
                    if (returnStatusCode.Equals(StatusCode.ErrorUserExist.ToString()))
                    {
                        this.lblPrompt.Text = this.hdfUserNameExits.Value;
                    }
                    // 用户编号重复
                    else if (returnStatusCode.Equals(StatusCode.ErrorCodeExist.ToString()))
                    {
                        this.lblPrompt.Text = this.hdfUserCodeExtis.Value;
                    }           
                    // 设置焦点
                    string checkInput = "<script>document.getElementById('" + this.txtUserName.ClientID + "').focus();</script>";
                    ClientScript.RegisterStartupScript(this.GetType(), "checkInput", checkInput);
                }
            }
            catch (Exception ex)
            {
                // 抛出异常
                this.lblPrompt.Text = ex.Message;
            }
        }
    }
    #endregion

    #region protected void btnCancel_Click(object sender, EventArgs e) 取消
    /// <summary>
    /// 取消
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Page.Response.Redirect("LossOfAccount.aspx");
    }
    #endregion

    #region protected void btnReturn_Click(object sender, EventArgs e) 返回
    /// <summary>
    /// 返回
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        // 判断是否带加载效果
        if (Utilities.IsLoading)
            // 转向返回页面（带加载效果）
            Page.Response.Redirect(Utilities.LoadingPageUrl + Server.UrlEncode(this.ReturnPage));
        else
            Page.Response.Redirect(this.ReturnPage);
    }
    #endregion
}